<template>
  <div class="page-container">
    <h1 class="metro-title"><i class="metro-icon"></i>数据统计</h1>

    <el-row :gutter="20">
      <el-col :span="6" v-for="card in statCards" :key="card.title">
        <el-card class="stat-card" :body-style="{ padding: '0px' }">
          <div class="stat-card-content">
            <div class="stat-card-icon" :style="{ backgroundColor: card.color }">
              <el-icon><component :is="card.icon" /></el-icon>
            </div>
            <div class="stat-card-info">
              <div class="stat-card-title">{{ card.title }}</div>
              <div class="stat-card-value">{{ card.value }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>站点类型分布</span>
            </div>
          </template>
          <div ref="stationTypeChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>线路站点数量</span>
            </div>
          </template>
          <div ref="lineStationChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>线路客流量对比</span>
            </div>
          </template>
          <div ref="passengerChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { Location, DataLine, DataAnalysis, Histogram } from '@element-plus/icons-vue'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Query from '@arcgis/core/rest/support/Query.js'

// 图表DOM引用
const stationTypeChartRef = ref<HTMLElement | null>(null)
const lineStationChartRef = ref<HTMLElement | null>(null)
const passengerChartRef = ref<HTMLElement | null>(null)

// 图表实例
let stationTypeChart: echarts.ECharts | null = null
let lineStationChart: echarts.ECharts | null = null
let passengerChart: echarts.ECharts | null = null

// 统计卡片数据
const statCards = reactive([
  {
    title: '地铁线路总数',
    value: '0',
    icon: DataLine,
    color: '#1976d2',
  },
  {
    title: '地铁站点总数',
    value: '0',
    icon: Location,
    color: '#ff9800',
  },
  {
    title: '换乘站点数量',
    value: '0',
    icon: DataAnalysis,
    color: '#4caf50',
  },
  {
    title: '日均客流总量',
    value: '0',
    icon: Histogram,
    color: '#e91e63',
  },
])

// 初始化图表
function initCharts() {
  // 站点类型分布饼图
  if (stationTypeChartRef.value) {
    stationTypeChart = echarts.init(stationTypeChartRef.value)
    stationTypeChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
      },
      legend: {
        orient: 'vertical',
        left: 10,
        data: ['普通站', '换乘站', '终点站'],
      },
      series: [
        {
          name: '站点类型',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: {
            show: false,
            position: 'center',
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold',
            },
          },
          labelLine: {
            show: false,
          },
          data: [
            { value: 0, name: '普通站' },
            { value: 0, name: '换乘站' },
            { value: 0, name: '终点站' },
          ],
        },
      ],
    })
  }

  // 线路站点数量柱状图
  if (lineStationChartRef.value) {
    lineStationChart = echarts.init(lineStationChartRef.value)
    lineStationChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: [],
        axisLabel: {
          interval: 0,
          rotate: 30,
        },
      },
      yAxis: {
        type: 'value',
        name: '站点数量',
      },
      series: [
        {
          name: '站点数量',
          type: 'bar',
          data: [],
          itemStyle: {
            color: function (params: any) {
              const colorList = [
                '#1976d2',
                '#ff9800',
                '#4caf50',
                '#e91e63',
                '#9c27b0',
                '#673ab7',
                '#3f51b5',
                '#2196f3',
                '#03a9f4',
                '#00bcd4',
              ]
              return colorList[params.dataIndex % colorList.length]
            },
          },
        },
      ],
    })
  }

  // 线路客流量对比条形图
  if (passengerChartRef.value) {
    passengerChart = echarts.init(passengerChartRef.value)
    passengerChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: {
        type: 'value',
        name: '日均客流量',
      },
      yAxis: {
        type: 'category',
        data: [],
        axisLabel: {
          interval: 0,
        },
      },
      series: [
        {
          name: '日均客流量',
          type: 'bar',
          data: [],
          itemStyle: {
            color: function (params: any) {
              const colorList = [
                '#1976d2',
                '#ff9800',
                '#4caf50',
                '#e91e63',
                '#9c27b0',
                '#673ab7',
                '#3f51b5',
                '#2196f3',
                '#03a9f4',
                '#00bcd4',
              ]
              return colorList[params.dataIndex % colorList.length]
            },
          },
        },
      ],
    })
  }
}

// 加载统计数据
async function loadStatisticsData() {
  try {
    // 创建地铁线路图层
    const subwayLineLayer = new FeatureLayer({
      url: 'https://services7.arcgis.com/WAsbhBMtbJ0DBeIA/arcgis/rest/services/地铁站点/FeatureServer/1',
      outFields: ['*'],
    })

    // 创建地铁站点图层
    const subwayStationLayer = new FeatureLayer({
      url: 'https://services7.arcgis.com/WAsbhBMtbJ0DBeIA/arcgis/rest/services/地铁站点/FeatureServer/0',
      outFields: ['*'],
    })

    // 查询所有线路
    const lineQuery = new Query()
    lineQuery.where = '1=1'
    lineQuery.outFields = ['*']
    const lineResults = await subwayLineLayer.queryFeatures(lineQuery)
    const lines = lineResults.features

    // 查询所有站点
    const stationQuery = new Query()
    stationQuery.where = '1=1'
    stationQuery.outFields = ['*']
    const stationResults = await subwayStationLayer.queryFeatures(stationQuery)
    const stations = stationResults.features

    // 更新统计卡片数据
    statCards[0].value = lines.length.toString()
    statCards[1].value = stations.length.toString()

    // 计算换乘站数量
    const transferStations = stations.filter(
      (station) => station.attributes.StationType === '换乘站',
    )
    statCards[2].value = transferStations.length.toString()

    // 计算总客流量 - 使用线路客流量而不是站点客流量总和
    let totalPassengers = 0;
    lines.forEach((line) => {
      totalPassengers! += Number(line.attributes.DailyPassengers)
    })
    statCards[3].value = totalPassengers.toString()

    // 更新站点类型分布图表
    if (stationTypeChart) {
      const stationTypes = {
        普通站: 0,
        换乘站: 0,
        终点站: 0,
      }

      stations.forEach((station) => {
        const type = station.attributes.StationType
        if (type in stationTypes) {
          stationTypes[type as keyof typeof stationTypes]++
        }
      })

      stationTypeChart.setOption({
        series: [
          {
            data: [
              { value: stationTypes['普通站'], name: '普通站' },
              { value: stationTypes['换乘站'], name: '换乘站' },
              { value: stationTypes['终点站'], name: '终点站' },
            ],
          },
        ],
      })
    }

    // 更新线路站点数量图表
    if (lineStationChart) {
      const lineNames = lines.map((line) => line.attributes.LineName)

      // 计算每条线路的实际站点数量
      const stationCounts = await Promise.all(
        lines.map(async (line) => {
          // 查询属于该线路的站点
          const lineStationQuery = new Query()
          lineStationQuery.where = `TransferLines LIKE '%${line.attributes.LineName}%'`
          lineStationQuery.outFields = ['*']
          const lineStationResults = await subwayStationLayer.queryFeatures(lineStationQuery)
          return lineStationResults.features.length
        }),
      )

      lineStationChart.setOption({
        xAxis: {
          data: lineNames,
        },
        series: [
          {
            data: stationCounts,
          },
        ],
      })
    }

    // 更新线路客流量对比图表
    if (passengerChart) {
      // 按客流量排序
      const sortedLines = [...lines].sort(
        (a, b) => (b.attributes.DailyPassengers || 0) - (a.attributes.DailyPassengers || 0),
      )

      const lineNames = sortedLines.map((line) => line.attributes.LineName)
      const passengerCounts = sortedLines.map((line) => line.attributes.DailyPassengers || 0)

      passengerChart.setOption({
        yAxis: {
          data: lineNames,
        },
        series: [
          {
            data: passengerCounts,
          },
        ],
      })
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 窗口大小变化时重新调整图表大小
function handleResize() {
  stationTypeChart?.resize()
  lineStationChart?.resize()
  passengerChart?.resize()
}

onMounted(() => {
  // 初始化图表
  initCharts()

  // 加载数据
  loadStatisticsData()

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)

  // 销毁图表实例
  stationTypeChart?.dispose()
  lineStationChart?.dispose()
  passengerChart?.dispose()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.metro-title {
  margin-bottom: 20px;
  color: #1976d2;
  font-size: 24px;
  display: flex;
  align-items: center;
}

.metro-icon {
  display: inline-block;
  width: 24px;
  height: 24px;
  margin-right: 8px;
  background-color: #1976d2;
  border-radius: 50%;
}

.stat-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.stat-card-content {
  display: flex;
  padding: 20px;
}

.stat-card-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  border-radius: 8px;
  margin-right: 15px;
  color: white;
  font-size: 24px;
}

.stat-card-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.chart-row {
  margin-top: 20px;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 350px;
  width: 100%;
}
</style>
